package com.casic.ccp.flying.youth.timeseriesdata.controller;

import com.casic.ccp.flying.youth.timeseriesdata.bo.ChartBo;
import com.casic.ccp.flying.youth.timeseriesdata.model.Data;
import com.casic.ccp.flying.youth.timeseriesdata.model.DataLoadInfo;
import com.casic.ccp.flying.youth.timeseriesdata.model.UploadFile;
import com.casic.ccp.flying.youth.timeseriesdata.result.GlobalResult;
import com.casic.ccp.flying.youth.timeseriesdata.result.ResultData;
import com.casic.ccp.flying.youth.timeseriesdata.service.DataLoadService;
import com.casic.ccp.flying.youth.timeseriesdata.service.FileService;
import com.casic.ccp.flying.youth.timeseriesdata.service.TaosService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ZeroCopyHttpOutputMessage;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 图表接口
 *
 * @Author: 贺坤
 * @Date: 2021/9/8 16:28
 */
@Controller
@RequestMapping("/chart")
public class ChartController {
    /**
     * 日志记录器
     */
    private static Logger LOGGER = LoggerFactory.getLogger(ChartController.class);
    @Autowired
    private DataLoadService dataLoadService;
    /**
     * 文件管理
     */
    @Autowired
    FileService fileService;
    /**
     * 涛思数据 服务
     */
    @Autowired
    TaosService taosService;

    /**
     * 查询图表数据
     *
     * @param chartBo
     * @return
     */
    @GetMapping
    @ResponseBody
    public GlobalResult selectTable(ChartBo chartBo) {
        GlobalResult globalResult = new GlobalResult();
        ResultData resultData = new ResultData();

        List<Data> select = taosService.select(chartBo.getName(), chartBo.getType(), chartBo.getStartTime(), chartBo.getEndTime(),chartBo.getWindowRatio());

        resultData.setTotal(Long.valueOf(select.size()));
        resultData.setItems(select);
        globalResult.setData(resultData);
        return globalResult;
    }

    /**
     * 通过文件系统的数据查询下载
     *
     * @param chartBo
     * @param response
     * @return
     */
    @GetMapping("downloadFile")
    @ResponseBody
    public Mono<Void> downloadFile(ChartBo chartBo, ServerHttpResponse response) {

        DataLoadInfo dataLoadInfo = dataLoadService.getById(chartBo.getId());
        UploadFile uploadFile = fileService.getById(dataLoadInfo.getFileTableId());

        File file = new File(new File(uploadFile.getPath()), uploadFile.getAnotherName() + FileService.SUFFIX);
        ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
        try {
            //输出文件名乱码问题处理
            response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + new String((uploadFile.getName().split("//.")[0] + "_" + chartBo.getStartTime() + "_" + chartBo.getEndTime() + FileService.SUFFIX).getBytes("UTF-8"), "iso-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);
        long position = (chartBo.getStartTime() - dataLoadInfo.getStartTime()) * 4;
        long count = (chartBo.getEndTime() - chartBo.getStartTime()) * 4;

        LOGGER.debug("文件总大小: {},开始位置: {},长度: {},最终: {}", file.length(), position, count, (position + count));
        // 判断是否是从开始时间下载
        if (chartBo.getStartTime() < dataLoadInfo.getStartTime() || chartBo.getEndTime() > dataLoadInfo.getEndTime()) {
            LOGGER.error("时间区间不对!");
            return Mono.just(null);
        }
        Mono<Void> voidMono = zeroCopyResponse.writeWith(file, position, count);
        return voidMono;
    }

    /**
     * 查询所有数据集
     *
     * @return
     */
    @GetMapping("/table")
    @ResponseBody
    public GlobalResult getTableList() {
        GlobalResult globalResult = new GlobalResult();
        ResultData resultData = new ResultData();
        List<DataLoadInfo> loadInfos = dataLoadService.list();
        resultData.setTotal(Long.valueOf(loadInfos.size()));
        resultData.setItems(loadInfos);
        globalResult.setData(resultData);
        return globalResult;
    }
}
